/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2008-2011, Salzburg Research. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * - Neither the name of the LMF library client Project nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * Contributor(s):
 * Stephanie Stroka
 *
 * File Info:
 * User: Stephanie Stroka
 * Date: 2011/08/19
 * Time: 18:04
 *
 * Project: lmflib
 */

package kiwi.connection;

import kiwi.config.ConfigurationServiceImpl;
import kiwi.config.api.ConfigurationService;
import kiwi.connection.api.LMFClient;
import kiwi.facading.model.resources.KiWiUriResource;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;

/**
 * @author Stephanie Stroka
 *         User: Stephanie Stroka
 *               (stephanie.stroka@salzburgresearch.at)
 *         Date: 19.08.2011
 *         Time: 18:05:45
 */
public class LMFClientImpl implements LMFClient {

    Logger log = LoggerFactory.getLogger(this.getClass());

    ConfigurationService configurationService;

    public LMFClientImpl() {
        configurationService = new ConfigurationServiceImpl();
    }


    private String constructHeader(DATATYPE dataType, MIMETYPE mimeType) {
        if(dataType == null) {
            dataType = DATATYPE.meta;
        }

        if(mimeType == null) {
            mimeType = MIMETYPE.n3;
        }

        StringBuilder acceptHeader = new StringBuilder();
        switch(mimeType) {
            case n3:
                acceptHeader.append("text/rdf+n3");
                break;
            case html:
                acceptHeader.append("text/html");
                break;
            case json:
                acceptHeader.append("application/json");
                break;
            case rdfxml:
                acceptHeader.append("application/rdf+xml");
                break;
        }
        acceptHeader.append(";");
        switch(dataType) {
            case meta:
                acceptHeader.append("rel=meta");
                break;
            case content:
                acceptHeader.append("rel=content");
                break;
        }
        return acceptHeader.toString();
    }

    @Override
    public InputStream getResource(KiWiUriResource subject, DATATYPE dataType, MIMETYPE mimeType) {

        if(subject == null) {
            return null;
        }

        URI uri = configurationService.getResourceConnection(subject);

        /*
        curl -X GET  -L -i -H "Accept: test/rdf+n3; rel=meta" \
             http://localhost:8080/LMF/resource/1234
         */
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet get = new HttpGet(uri);
        get.setHeader("Accept", constructHeader(dataType, mimeType));

        try {
            HttpResponse response = httpClient.execute(get);

            int status = response.getStatusLine().getStatusCode();

            /* The resource was not found -> return an empty set of triples */
            if(status < 200 || status >= 400) {
                return null;
            }

            if(status >= 300 && status < 400) {
                String redirectLocation;
                Header locationHeader = response.getFirstHeader("location");
                if (locationHeader != null) {
                    log.info("location: {}", locationHeader.getValue());
                    redirectLocation = locationHeader.getValue();
                } else {
                // The response is invalid and did not provide the new location for
                // the resource.  Report an error or possibly handle the response
                // like a 404 Not Found error.
                    log.error("Location not found");
                    return null;
                }
                URI redirect_uri = new URI(redirectLocation);
                HttpGet redirect_get = new HttpGet(redirect_uri);
                response = httpClient.execute(redirect_get);

                status = response.getStatusLine().getStatusCode();
                log.info("status: {}, reason phrase: {}", status, response.getStatusLine().getReasonPhrase());

                if(status != 200) {
                    return null;
                }

            }
            InputStream is = response.getEntity().getContent();
            return is;

        } catch (HttpException e) {
                e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int putResource() {
        return 0;
    }

    public int postResource() {
        return 0;
    }

    public int deleteResource() {
        return 0;
    }
}
